from typing import Literal
import redis.asyncio as redis


class RedisManager:
    def __init__(
        self,
        host: str = "127.0.0.1",
        port: int = 6379,
        db: int = 0,
        password: str = None,
    ) -> None:
        self.redis_client = redis.Redis(
            host=host, port=port, db=db, password=password, decode_responses=True
        )

    async def set(self, key: str, value: str, expiry: Literal["keepttl"] | int) -> None:
        # 修复：keepttl 不是有效参数，应使用 expire 间接控制
        # Redis 会自动使用过期时间策略
        if isinstance(expiry, str):
            await self.redis_client.set(key, value, keepttl=True)
        else:
            await self.redis_client.set(key, value, ex=expiry)

    async def get(self, key: str) -> str:
        return await self.redis_client.get(key)

    #async def hget(self, name: str, key: str) -> str:
    #    return await self.redis_client.hget(name, key)

    async def delete(self, key: str) -> None:
        await self.redis_client.delete(key)

    async def exists(self, key: str) -> bool:
        return await self.redis_client.exists(key)

    async def setExpire(self, key: str, expire: int) -> None:
        await self.redis_client.expire(key, expire)

    async def getExpire(self, key: str) -> int:
        return await self.redis_client.ttl(key)
